import BscDapp from '@obsidians/bsc-dapp'//取得TRX余额
import lpAbi from './lpAbi.json'
import fireAbi from './fireAbi.json'
import pancakeAbi from './pancakeAbi.json'
import bnbAbi from './bnbAbi.json'
import lsdAbi from './lsdAbi.json'
import usdtAbi from './usdtAbi.json'
import bpoolAbi from './bpoolAbi.json'
import Web3  from 'web3'
import routeAbi from './routeAbi.json'
import Req from './request'
import Msg from './message'
import Lang from './extend'
import { empty } from 'statuses'

function updateNetwork(network) {
	alert(network.isBscMainnet)
	if (network.isBscMainnet) {
		this.network = 'Mainnet'
	} else if (network.isBscTestnet) {
		this.network = 'Testnet'
	} else {
		this.network = ''
	}
}

async function bscInit() {
	const dapp =  new BscDapp(); // {extension: 'BinanceChainWallet'}
	await dapp.enableBrowserExtension();
	return dapp;
}
 
async function getBscBalance(address) {
	var dapp = await bscInit();
	const balance =  await dapp.rpc.getBalance(address)
	console.log('Balance:', balance.toString())
	return balance;
}

async function getAccount() {
	var dapp = await bscInit();
	return dapp.currentAccount;
}

async function contractBpoolInit(){
	var dapp = await bscInit();	
	let fireContractAddress = '0x99bbA657f2BbC93c02D617f8bA121cB8Fc104Acf';
	
	let webThree = new Web3(ethereum);
	let bpoolContract = new webThree.eth.Contract(bpoolAbi, fireContractAddress);
	return fireContract;
}

async function contractInit(){
	var dapp = await bscInit();	
	let fireContractAddress = '0xf8C9e60Afc5040bFA71b866F10c717055226644B';
	let webThree = new Web3(new Web3.providers.HttpProvider("https://bsc-dataseed.binance.org"));
	let fireContract = new webThree.eth.Contract(fireAbi, fireContractAddress);
	return fireContract;
}

async function contractUsdtInit(address){
	var dapp = await bscInit();
	const usdtTokenAddress = "0x55d398326f99059fF775485246999027B3197955";
	const contractAddress    = usdtTokenAddress;
	const web3             = new Web3(new Web3.providers.HttpProvider("https://bsc-dataseed.binance.org"));
	let usdtContract = new web3.eth.Contract(usdtAbi, contractAddress);
	var uBalance = await usdtContract.methods.balanceOf(address).call();
	
	return web3.utils.fromWei(uBalance,'ether');
}

async function contractLsdInit(address){
	var dapp = await bscInit();
	const lsdTokenAddress = "0xcD1B51b87a8a7137D6421bA5A976225187a26777";
	const contractAddress    = lsdTokenAddress;
	const web3             = new Web3(new Web3.providers.HttpProvider("https://bsc-dataseed.binance.org"));
	let lsdContract = new web3.eth.Contract(lsdAbi, contractAddress);
	var uBalance = await lsdContract.methods.balanceOf(address).call();
	
	return web3.utils.fromWei(uBalance,'ether');
}

async function getfirebalance(address){
	 let FIRE_ABI = fireAbi;
	 let FIRE_Contract_Address = '0x126623553b4cFa513115f0E94A6acBd3F1EB7399';
	 let web_3 = new Web3(ethereum); 
	 let FIRE_Contract = new web_3.eth.Contract(FIRE_ABI, FIRE_Contract_Address);
	 await FIRE_Contract
}

async function getPrice() {
	var dapp = await bscInit();
	
	const usdtTokenAddress = "0x55d398326f99059fF775485246999027B3197955";
	const fireTokenAddress = "0x8497A082B3122548A5a435FaFF2bb0d2E5531CC5";
	
	const web3 = new Web3('https://bsc-dataseed.binance.org');
	
	const pancakeSwap = new web3.eth.Contract(
	    pancakeAbi,
	    "0x10ED43C718714eb63d5aA57B78B54704E256024E"
	);
	const amountInUSDT = web3.utils.toBN(web3.utils.toWei('1'));
	const fireOutput = await pancakeSwap.methods.getAmountsOut(amountInUSDT, [usdtTokenAddress, fireTokenAddress]).call();
	
	// console.log(fireOutput);
	return fireOutput;	
}
function getHashResult(web3,hash,url,amount,fuwen){
     web3.eth.getTransactionReceipt(hash,function(error, result){
		if(!result || result=='undefined'){
			console.log('===');
			 getHashResult(web3,hash,url,amount,fuwen);
		}else{
			var sendData = {
				'money':amount,
				'hash':hash
			};
			Req._post(
			url,
			sendData,
			true,
			res_pay => {
				if (res_pay.code == 200) {
					Req._post(
					'/api/service/buyRune',
					{number:fuwen},
					true,
					res_pay => {
						if (res_pay.code == 200) {
							Msg.Success(Lang.lang('prompt_4'))
						}else{
							Msg.Fail(res_pay.msg)
						}
						uni.hideLoading();
					},
					true)
				}else{
					Msg.Fail(res_pay.msg)
				}
				uni.hideLoading();
			},
			true)
		}
	})
}
function getHashResult1(web3,hash,url,amount,fuwen){
     web3.eth.getTransactionReceipt(hash,function(error, result){
		if(!result || result=='undefined'){
			console.log('===');
			 getHashResult1(web3,hash,url,amount,fuwen);
		}else{
			var sendData = {
				'money':amount,
				'hash':hash
			};
			Req._post(
			url,
			sendData,
			true,
			res_pay => {
				if (res_pay.code == 200) {
					// Req._post(
					// '/api/service/buyRune',
					// {number:fuwen},
					// true,
					// res_pay => {
					// 	if (res_pay.code == 200) {
					// 		Msg.Success(Lang.lang('prompt_4'))
					// 	}else{
					// 		Msg.Fail(res_pay.msg)
					// 	}
					// 	uni.hideLoading();
					// },
					// true)
				}else{
					Msg.Fail(res_pay.msg)
				}
				uni.hideLoading();
			},
			true)
		}
	})
}
async function lsdTransfer(address, receiver,contractAddress, amount, url, fuwen,sendData={}) {
	uni.showLoading({
		title: 'loading',
		mask:true
	});
 	var dapp = await bscInit();
 	var from = address;
 	var to = receiver;

	var _value = amount
 	var lsdAddress = contractAddress;
	
	window.web3 = new Web3(ethereum); 
 	var web3 = window.web3;
	
 	let bnbContract = new web3.eth.Contract(lsdAbi, lsdAddress);	 	
 	const transaction = await bnbContract.methods.transfer(to,web3.utils.toWei(_value,'Ether'));
	
	var balance = 0 
	await web3.eth.getBalance(from, function(error,result){
		if(error){
			alert(error);
			console.log(error)
		}else{
			balance = result;
			console.log(result)
		}
	});
	
	if(balance <= 5000) {
		Msg.Fail(Lang.lang('insufficient'));
		uni.hideLoading();
		return false;
	}
	
	var needAmount = web3.utils.toWei(_value,'Ether');
	var uBalance = await bnbContract.methods.balanceOf(from).call();
	
	if(parseInt(uBalance) < parseInt(needAmount)) {
		Msg.Fail(Lang.lang('insufficientLSD'));
		uni.hideLoading();
		return false;
	}
	
	var gas = await transaction.estimateGas({from});
	let gasPrice = await web3.eth.getGasPrice();
	
	var data = await transaction.send({
		from,
		gas,
		gasPrice: gasPrice * 1.5
	}, async function(error, hash){
		if(!hash || hash=='undefined') {
			uni.hideLoading();
			return false;
		}
	    getHashResult(web3,hash,url,amount,fuwen);
		
 	});
 	return data.transactionHash;
	
}

async function usdtTransfer(address, receiver, amount, url, fuwen,sendData={}) {
	uni.showLoading({
		title: 'loading',
		mask:true
	});
 	var dapp = await bscInit();
 	var from = address;
 	var to = receiver;

	var _value = amount
 	var usdtAddress = '0x55d398326f99059fF775485246999027B3197955';
	
	window.web3 = new Web3(ethereum); 
 	var web3 = window.web3;
 	let bnbContract = new web3.eth.Contract(usdtAbi, usdtAddress);	 	
 	const transaction = await bnbContract.methods.transfer(to,web3.utils.toWei(_value,'Ether'));
	
	var balance = 0 
	await web3.eth.getBalance(from, function(error,result){
		if(error){
			alert(error);
			console.log(error)
		}else{
			balance = result;
			console.log(result)
		}
	});
	
	if(balance <= 5000) {
		Msg.Fail(Lang.lang('insufficient'));
		uni.hideLoading();
		return false;
	}
	
	var needAmount = web3.utils.toWei(_value,'Ether');
	var uBalance = await bnbContract.methods.balanceOf(from).call();
	
	if(parseInt(uBalance) < parseInt(needAmount)) {
		Msg.Fail(Lang.lang('insufficientLSD'));
		uni.hideLoading();
		return false;
	}
	
	var gas = await transaction.estimateGas({from});
	let gasPrice = await web3.eth.getGasPrice();
	var data = await transaction.send({
		from,
		gas,
		gasPrice: gasPrice * 1.5
	}, function(error, hash){
		if(!hash || hash=='undefined') {
			uni.hideLoading();
			return false;
		}
		getHashResult1(web3,hash,url,amount,fuwen);
 	});
 	return data.transactionHash;
}

async function cakeLpTransfer(address, receiver, amount, url, sendData={}) {
 	var dapp = await bscInit();
 	var from = address;
 	var to = receiver;

	var _value = amount
 	var usdtAddress = '0x55d398326f99059fF775485246999027B3197955';
	
 	let web_3 = new Web3(ethereum); 	
 	let bnbContract = new web_3.eth.Contract(lpAbi, usdtAddress);	 	
 	const transaction = await bnbContract.methods.transfer(to,web_3.utils.toWei(_value,'Ether'));
	
	var balance = await web_3.eth.getBalance(from);
	if(balance <= 5000) {
		Msg.Fail(Lang.lang('insufficient')); //Your BNB balance is not enough for handling fees, please recharge and participate 
		return false;
	}
	var gas = await transaction.estimateGas({from});
	var data = await transaction.send({
		from,
		gas
	}, function(error, hash){
 		console.log(error)
 		console.log(hash);
 		uni.setStorageSync('landbox_hash', hash);
 		if(!hash || hash=='undefined') {
 			return false;
 		}
 		let requestData = {};
 		if(JSON.stringify(sendData) != '{}') {
 			sendData = Object.assign({txId:hash}, sendData);
 			requestData = sendData
 		} else {
 			requestData = {from:from,to:to, txId:hash,money:amount}
 		}
 		Req._post(
 		url,
 		requestData,
 		true,
 		res_pay => {
 			if (res_pay.code == 1) {
 				Msg.Success(res_pay.msg)
 			}else{
 				Msg.Fail(res_pay.msg)
 			}
 		},
 		true)
 	});
 	return data.transactionHash;
}

async function usdtBatchTransfer(address,amount, url, sendData={}) {
 	var dapp = await bscInit();
 	
	var from = address;
	var usdtAddress = '0x55d398326f99059fF775485246999027B3197955';
	
 	let web_3 = new Web3(ethereum); 	
 	let bnbContract = new web_3.eth.Contract(usdtAbi, usdtAddress);	 	
	var addressArr = ['0x70997970C51812dc3A010C7d01b50e0d17dc79C8', '0x976EA74026E726554dB657fA54763abd0C3a0aa9']; 
	for(let to of addressArr){
		console.log(to);
		if(to == '0x70997970C51812dc3A010C7d01b50e0d17dc79C8') {
			var _value = String(amount * 0.9);
		} else {
			var _value = String(amount * 0.1);
		}
		
		console.log(_value);
		const transaction = await bnbContract.methods.transfer(to,web_3.utils.toWei(_value,'ether'));
		var gas = await transaction.estimateGas({from});
		var data = await transaction.send({
			from,
			gas,
		}, function(error, hash){
			console.log(error)
			console.log(hash);
			uni.setStorageSync('landbox_hash', hash);
			if(!hash || hash=='undefined') {
				return false;
			}
			let requestData = {};
			if(JSON.stringify(sendData) != '{}') {
				sendData = Object.assign({txId:hash}, sendData);
				requestData = sendData
			} else {
				requestData = {from:from,to:to, txId:hash,money:amount}
			}
			Req._post(
			url,
			requestData,
			true,
			res_pay => {
				if (res_pay.code == 1) {
					Msg.Success(res_pay.msg)
				}else{
					Msg.Fail(res_pay.msg)
				}
			},
			true)
		});
	}
 	return data.transactionHash;
}	

async function bscContractTransfer(address, amount, url, sendData={}) {
	var dapp = await bscInit();	
	var from = address;
	
	var _value = amount
	var sender = address	
	var recipient = '0x000000000000000000000000000000000000dEaD';
	var address = '0xc9c415d666A2d2CFF348a0081145346E6bA50643';
	
	
	let FIRE_ABI = fireAbi;
	let FIRE_Contract_Address = address;
	let web_3 = new Web3(ethereum); 
	let FIRE_Contract = new web_3.eth.Contract(FIRE_ABI, FIRE_Contract_Address);
	// const transaction = await FIRE_Contract.methods.transfer(recipient,web_3.utils.toBN(_value));
	
	const transaction = await FIRE_Contract.methods.transfer(recipient,web_3.utils.toWei(_value,'Ether'));
	var balance = await web_3.eth.getBalance(from);
	if(balance <= 5000) {
		Msg.Fail(Lang.lang('insufficient')); //Your BNB balance is not enough for handling fees, please recharge and participate 
		return false;
	}
	var gas = await transaction.estimateGas({from});
	var data = await transaction.send({
		from, 
		gas,
	},function(error, hash){
		// uni.setStorageSync('landbox_hash', hash);
		if(!hash || hash=='undefined') {
			return false;
		}
		let requestData = {};
		if(JSON.stringify(sendData) != '{}') {
			sendData = Object.assign({txId:hash}, sendData);
			requestData = sendData
		} else {
			requestData = {txId:hash,amount:amount}
		}
		Req._post(
		url,
		requestData,
		true,
		res_pay => {
			if (res_pay.code == 1) {
				Msg.Success(res_pay.msg)
			}else{
				Msg.Fail(res_pay.msg)
			}
		},
		true)
	});
	return data.transactionHash
}

module.exports = {   
	getBscBalance,
	bscContractTransfer,
	getAccount,
	usdtTransfer,
	getPrice,
	contractInit,
	contractUsdtInit,
	contractLsdInit,
	contractBpoolInit,
	usdtBatchTransfer,
	cakeLpTransfer,
	bscInit,
	lsdTransfer
}
